package com.hph.demo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import java.util.concurrent.TimeUnit;

/**
 * Netty 心跳检测服务端
 * @author 10499
 */
public class NettyHeartbeatServerDemo {

    public static void main(String[] args) throws InterruptedException {

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new StringEncoder());
                        // 设置读时间没 2 秒触发一次，如果没有触发的话就说明超时
                        pipeline.addLast(new IdleStateHandler(2, 0, 0,  TimeUnit.SECONDS));
                        pipeline.addLast(new MyServerSocketHandler());
                    }
                });
        ChannelFuture channelFuture = serverBootstrap.bind("127.0.0.1", 8888).sync();
        System.out.println("服务端已启动！！！");
        channelFuture.channel().closeFuture().sync();
    }

    static class MyServerSocketHandler extends SimpleChannelInboundHandler<String> {

        private int n;

        @Override
        public void channelActive(ChannelHandlerContext ctx) {

            System.out.println("有客户端连接！！！1");
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, String msg) {

            System.out.println("收到心跳信息：" + msg);
        }

        /**
         * 如果心跳检测超时的话就会进这
         * @param ctx
         * @param evt
         */
        @Override
        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {

            IdleStateEvent idleStateEvent = (IdleStateEvent)evt;
            if (idleStateEvent.state() == IdleState.READER_IDLE) {
                n++;
            }
            // 超过三次就关闭客户端
            if(n > 3) {
                System.out.println("客户端失去连接了！！！");
                ctx.channel().close();
            }
        }
    }
}
